<template>
  <div class="template-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon>
            <Document />
          </el-icon>
          我的模板
        </h1>
        <p class="page-description">管理您创建的所有模板，设置公开/私有状态</p>
      </div>
      <div class="header-stats">
        <div class="stat-item">
          <span class="stat-number">{{ userTemplates.length }}</span>
          <span class="stat-label">我的模板</span>
        </div>
        <div class="stat-item">
          <span class="stat-number">{{ publicTemplatesCount }}</span>
          <span class="stat-label">公开模板</span>
        </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="search-section">
        <el-input v-model="searchKeyword" placeholder="搜索模板..." clearable style="width: 300px;" @input="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon>
            <Plus />
          </el-icon>
          创建模板
        </el-button>
        <el-button @click="importTemplate">
          <el-icon>
            <Upload />
          </el-icon>
          导入模板
        </el-button>
      </div>
    </div>

    <!-- 模板列表 -->
    <div class="template-grid" v-loading="loading">
      <el-card v-for="template in filteredTemplates" :key="template.id" class="template-card" shadow="hover">
        <template #header>
          <div class="template-header">
            <div class="template-title">
              <h3>{{ template.name }}</h3>
              <div class="template-badges">
                <el-tag :type="template.isPublic ? 'success' : 'warning'" size="small">
                  {{ template.isPublic ? '公开' : '私有' }}
                </el-tag>
                <el-tag v-if="template.featured" type="danger" size="small">
                  精选
                </el-tag>
              </div>
            </div>
            <el-dropdown @command="handleTemplateAction">
              <el-button type="text" size="small">
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'use', template }">
                    使用模板
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'edit', template }">
                    编辑模板
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'togglePublic', template }">
                    {{ template.isPublic ? '设为私有' : '设为公开' }}
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'export', template }">
                    导出模板
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', template }" divided>
                    删除模板
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>

        <div class="template-content">
          <p class="template-description">{{ template.description }}</p>

          <div class="template-software">
            <h4>包含软件 ({{ template.softwareList?.length || 0 }})</h4>
            <div class="software-tags">
              <el-tag v-for="software in template.softwareList?.slice(0, 3)" :key="software.id" size="small"
                type="info">
                {{ software.displayName }}
              </el-tag>
              <el-tag v-if="template.softwareList?.length > 3" size="small" type="info">
                +{{ template.softwareList.length - 3 }}
              </el-tag>
            </div>
          </div>

          <div class="template-meta">
            <div class="meta-item">
              <el-icon>
                <User />
              </el-icon>
              <span>{{ template.createdByNickname || template.createdBy || '匿名用户' }}</span>
            </div>
            <div class="meta-item">
              <el-icon>
                <Download />
              </el-icon>
              <span>{{ template.downloadCount || 0 }} 次使用</span>
            </div>
            <div class="meta-item">
              <el-icon>
                <Calendar />
              </el-icon>
              <span>{{ formatDate(template.createdAt) }}</span>
            </div>
          </div>
        </div>

        <template #footer>
          <div class="template-actions">
            <el-button type="primary" size="small" @click="useTemplate(template)">
              使用模板
            </el-button>
            <el-button size="small" @click="previewTemplate(template)">
              预览
            </el-button>
          </div>
        </template>
      </el-card>

      <!-- 空状态 -->
      <div v-if="!loading && filteredTemplates.length === 0" class="empty-state">
        <el-empty description="没有找到匹配的模板">
          <el-button type="primary" @click="showCreateDialog = true">
            创建第一个模板
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 创建/编辑模板对话框 -->
    <el-dialog v-model="showCreateDialog" :title="editingTemplate ? '编辑模板' : '创建模板'" width="600px" @close="resetForm">
      <el-form :model="templateForm" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" :maxlength="TEMPLATE_NAME_MAX_LENGTH"
            show-word-limit />
        </el-form-item>

        <el-form-item label="模板描述" prop="description">
          <el-input v-model="templateForm.description" type="textarea" :rows="3" placeholder="请输入模板描述"
            :maxlength="TEMPLATE_DESCRIPTION_MAX_LENGTH" show-word-limit />
        </el-form-item>

        <el-form-item label="模板分类" prop="category">
          <el-select v-model="templateForm.category" placeholder="请选择模板分类" style="width: 100%">
            <el-option v-for="category in templateCategories" :key="category.code" :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标系统" prop="targetOs">
          <el-select v-model="templateForm.targetOs" placeholder="请选择目标操作系统" style="width: 100%">
            <el-option label="Windows" value="windows" />
            <el-option label="Linux" value="linux" />
            <el-option label="macOS" value="macos" />
            <el-option label="跨平台" value="cross-platform" />
          </el-select>
        </el-form-item>

        <el-form-item label="模板标签" prop="tags">
          <div class="tags-input">
            <el-tag v-for="tag in templateForm.tags" :key="tag" closable @close="removeTag(tag)">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="tagInput" v-model="inputValue" size="small" style="width: 100px"
              @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
            <el-button v-else size="small" type="text" @click="showInput">
              + 添加标签
            </el-button>
          </div>
          <div class="tags-tips">
            <el-text type="info" size="small">
              标签有助于其他用户找到您的模板（最多5个标签）
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="是否公开">
          <el-switch v-model="templateForm.isPublic" />
          <span class="form-hint">公开模板可以被其他用户使用</span>
        </el-form-item>

        <el-form-item label="包含软件">
          <div class="software-selection">
            <div class="software-selection-header">
              <span class="software-count">
                {{ selectedSoftware.length === 0 ? '还没有选择任何软件' : `已选择 ${selectedSoftware.length} 个软件` }}
              </span>
              <el-button type="primary" size="small" @click="goToSoftwareSelection">
                <el-icon>
                  <Plus />
                </el-icon>
                选择软件
              </el-button>
            </div>
            <div v-if="selectedSoftware.length > 0" class="selected-software-list">
              <el-tag v-for="software in selectedSoftware" :key="software.id" closable
                @close="removeSoftwareFromTemplate(software.id)">
                {{ software.displayName }} v{{ software.version }}
              </el-tag>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="saveTemplate" :loading="saving">
            {{ editingTemplate ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="模板预览" width="800px">
      <div v-if="previewingTemplate" class="template-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">
            {{ previewingTemplate.name }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ previewingTemplate.createdBy }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(previewingTemplate.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="使用次数">
            {{ previewingTemplate.downloadCount || 0 }} 次
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ previewingTemplate.description }}
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin: 20px 0 12px 0;">包含的软件</h4>
        <el-table :data="previewingTemplate.softwareList" style="width: 100%">
          <el-table-column label="软件名称">
            <template #default="scope">
              {{ scope.row.displayName || scope.row.name || '未知软件' }}
            </template>
          </el-table-column>
          <el-table-column label="版本" width="120">
            <template #default="scope">
              {{ scope.row.version || 'latest' }}
            </template>
          </el-table-column>
          <el-table-column label="分类" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getCategoryType(scope.row.category)">
                {{ scope.row.category || '其他' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPreviewDialog = false">关闭</el-button>
          <el-button type="primary" @click="useTemplate(previewingTemplate)">
            使用此模板
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import
  {
    Calendar,
    Document,
    Download,
    MoreFilled,
    Plus,
    Search,
    Upload,
    User
  } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { TEMPLATE_CATEGORIES, getCategoryType } from '../constants/templateCategories'
import { useSoftwareStore } from '../stores/software'
import { useUserStore } from '../stores/user'
import { ApiClient } from '../utils/api'

// 常量定义
const TEMPLATE_NAME_MAX_LENGTH = 50
const TEMPLATE_DESCRIPTION_MAX_LENGTH = 500
const AUTO_OPEN_DIALOG_DELAY = 500

const router = useRouter()
const softwareStore = useSoftwareStore()
const userStore = useUserStore()

// 模板分类配置
const templateCategories = TEMPLATE_CATEGORIES

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const searchKeyword = ref('')
const templates = ref([])

const showCreateDialog = ref(false)
const showPreviewDialog = ref(false)
const editingTemplate = ref(null)
const previewingTemplate = ref(null)

// Tags相关的响应式数据
const inputVisible = ref(false)
const inputValue = ref('')
const tagInput = ref()

const templateForm = ref({
  name: '',
  description: '',
  category: '',
  targetOs: '',
  tags: [],
  isPublic: true
})

const formRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: TEMPLATE_NAME_MAX_LENGTH, message: `模板名称长度在 2 到 ${TEMPLATE_NAME_MAX_LENGTH} 个字符`, trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入模板描述', trigger: 'blur' },
    { min: 10, max: TEMPLATE_DESCRIPTION_MAX_LENGTH, message: `模板描述长度在 10 到 ${TEMPLATE_DESCRIPTION_MAX_LENGTH} 个字符`, trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择模板分类', trigger: 'change' }
  ],
  targetOs: [
    { required: true, message: '请选择目标系统', trigger: 'change' }
  ]
}

const formRef = ref()

// 计算属性
const selectedSoftware = computed(() => softwareStore.selectedSoftware)

const userTemplates = computed(() =>
{
  // 由于fetchTemplates已经只获取当前用户的模板，所以直接返回所有模板
  return templates.value
})

const publicTemplatesCount = computed(() =>
{
  return userTemplates.value.filter(template => template.isPublic).length
})

const filteredTemplates = computed(() =>
{
  let filtered = userTemplates.value

  if (searchKeyword.value)
  {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(keyword) ||
      template.description.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 获取模板列表 - 获取当前用户的模板
const fetchTemplates = async (forceRefresh = false) =>
{
  // 如果已有数据且不是强制刷新，则跳过请求
  if (!forceRefresh && templates.value.length > 0)
  {
    return
  }

  try
  {
    loading.value = true

    // 开源版本跳过模板API调用
    const isOpenSourceVersion = true // 开源版本标识
    if (isOpenSourceVersion)
    {
      console.log('📊 开源版本跳过我的模板API调用')
      templates.value = []
      ElMessage.info('开源版本暂不支持模板管理功能')
      return
    }

    const response = await ApiClient.get('/templates/my')
    if (response.success)
    {
      templates.value = response.data || []
      console.log('获取到我的模板数量:', templates.value.length)
    } else
    {
      ElMessage.error('获取模板列表失败：' + response.message)
    }
  } catch (error)
  {
    console.error('获取模板列表失败:', error)

    // 根据错误类型提供更具体的错误信息
    let errorMessage = '获取模板列表失败'
    if (error.response)
    {
      // 服务器返回错误状态码
      if (error.response.status === 401)
      {
        errorMessage = '请先登录'
      } else if (error.response.status === 403)
      {
        errorMessage = '没有权限访问'
      } else if (error.response.status >= 500)
      {
        errorMessage = '服务器内部错误，请稍后重试'
      } else
      {
        errorMessage = error.response.data?.message || '获取模板列表失败'
      }
    } else if (error.request)
    {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置'
    }

    ElMessage.error(errorMessage)
  } finally
  {
    loading.value = false
  }
}

// 生命周期
onMounted(() =>
{
  fetchTemplates()

  // 检查是否有来自软件选择页面的待创建模板数据
  const pendingData = sessionStorage.getItem('pendingTemplateData')
  if (pendingData)
  {
    try
    {
      const templateData = JSON.parse(pendingData)
      if (templateData.autoCreate && templateData.softwareList)
      {
        // 预填充软件列表到store
        softwareStore.clearSelectedSoftware()
        templateData.softwareList.forEach(software =>
        {
          softwareStore.addSoftware(software)
        })

        // 自动打开创建模板弹窗
        setTimeout(() =>
        {
          showCreateDialog.value = true
        }, AUTO_OPEN_DIALOG_DELAY) // 延迟一点确保页面加载完成

        // 清除sessionStorage中的数据
        sessionStorage.removeItem('pendingTemplateData')
      }
    } catch (error)
    {
      console.error('解析待创建模板数据失败:', error)
      sessionStorage.removeItem('pendingTemplateData')
    }
  }

  // 检查是否需要自动打开创建弹窗（来自模板广场或个人主页）
  const autoOpenFlag = sessionStorage.getItem('autoOpenCreateDialog')
  if (autoOpenFlag === 'true')
  {
    setTimeout(() =>
    {
      showCreateDialog.value = true
    }, AUTO_OPEN_DIALOG_DELAY)

    // 清除标记
    sessionStorage.removeItem('autoOpenCreateDialog')
  }

  // 检查是否从软件选择页面返回
  const formState = sessionStorage.getItem('templateFormState')
  if (formState)
  {
    try
    {
      const state = JSON.parse(formState)
      if (state.returnToCreateDialog)
      {
        // 恢复表单状态
        templateForm.value = state.templateForm
        editingTemplate.value = state.editingTemplate

        // 自动打开创建模板弹窗
        setTimeout(() =>
        {
          showCreateDialog.value = true
        }, AUTO_OPEN_DIALOG_DELAY)

        // 清除状态
        sessionStorage.removeItem('templateFormState')
      }
    } catch (error)
    {
      console.error('解析表单状态失败:', error)
      sessionStorage.removeItem('templateFormState')
    }
  }
})

// 方法
const handleSearch = () =>
{
  // 搜索逻辑已在计算属性中处理
}

const handleTemplateAction = ({ action, template }) =>
{
  switch (action)
  {
    case 'use':
      useTemplate(template)
      break
    case 'edit':
      editTemplate(template)
      break
    case 'togglePublic':
      toggleTemplatePublic(template)
      break
    case 'export':
      exportTemplate(template)
      break
    case 'delete':
      deleteTemplate(template)
      break
  }
}

const useTemplate = async (template) =>
{
  try
  {
    // 调用后端API记录使用次数
    const response = await ApiClient.post(`/templates/${template.id}/use`)

    if (response.success)
    {
      // 清空当前选择
      softwareStore.clearSelectedSoftware()

      // 添加模板中的软件
      template.softwareList.forEach(software =>
      {
        softwareStore.addSoftware({
          id: software.id,
          name: software.name,
          displayName: software.displayName,
          latestVersion: { version: software.version }
        })
      })

      // 更新本地模板的使用次数显示
      template.downloadCount = (template.downloadCount || 0) + 1

      ElMessage.success(`已应用模板：${template.name}`)
      router.push('/software')
    } else
    {
      throw new Error(response.message || '使用模板失败')
    }
  } catch (error)
  {
    console.error('使用模板失败:', error)
    ElMessage.error('使用模板失败: ' + error.message)
  }
}

const editTemplate = (template) =>
{
  editingTemplate.value = template
  templateForm.value = {
    name: template.name,
    description: template.description,
    category: template.category || '',
    targetOs: template.targetOs || '',
    tags: template.tags || [],
    isPublic: template.isPublic
  }

  // 设置软件选择
  softwareStore.clearSelectedSoftware()
  template.softwareList.forEach(software =>
  {
    softwareStore.addSoftware(software)
  })

  showCreateDialog.value = true
}

const toggleTemplatePublic = async (template) =>
{
  try
  {
    const action = template.isPublic ? '设为私有' : '设为公开'
    await ElMessageBox.confirm(
      `确定要将模板"${template.name}"${action}吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await ApiClient.put(`/templates/${template.id}/visibility`, {
      isPublic: !template.isPublic
    })

    if (response.success)
    {
      template.isPublic = !template.isPublic
      ElMessage.success(`${action}成功`)
    } else
    {
      throw new Error(response.message || `${action}失败`)
    }
  } catch (error)
  {
    if (error.message !== 'cancel')
    {
      ElMessage.error('操作失败: ' + error.message)
    }
  }
}

const previewTemplate = (template) =>
{
  console.log('预览模板数据:', template)
  console.log('软件列表:', template.softwareList)
  previewingTemplate.value = template
  showPreviewDialog.value = true
}

const exportTemplate = (template) =>
{
  const data = JSON.stringify(template, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)

  const link = document.createElement('a')
  link.href = url
  link.download = `${template.name}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  URL.revokeObjectURL(url)
  ElMessage.success('模板导出成功')
}

const deleteTemplate = async (template) =>
{
  try
  {
    await ElMessageBox.confirm(
      `确定要删除模板"${template.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用API删除模板
    const response = await ApiClient.delete(`/templates/${template.id}`)
    if (response.success)
    {
      const index = templates.value.findIndex(t => t.id === template.id)
      if (index > -1)
      {
        templates.value.splice(index, 1)
      }
      ElMessage.success('模板删除成功')
    } else
    {
      ElMessage.error('模板删除失败: ' + response.message)
    }
  } catch (error)
  {
    if (error !== 'cancel')
    {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败: ' + (error.message || '未知错误'))
    }
    // 用户取消删除时不显示错误
  }
}

const saveTemplate = async () =>
{
  if (!formRef.value) return

  try
  {
    await formRef.value.validate()

    if (selectedSoftware.value.length === 0)
    {
      ElMessage.warning('请至少选择一个软件')
      return
    }

    saving.value = true

    // 准备模板数据
    const templateData = {
      name: templateForm.value.name,
      description: templateForm.value.description,
      category: templateForm.value.category,
      targetOs: templateForm.value.targetOs,
      tags: templateForm.value.tags,
      isPublic: templateForm.value.isPublic,
      softwareList: selectedSoftware.value.map(software => ({
        id: software.id,
        name: software.name,
        displayName: software.displayName,
        version: software.version,
        category: software.category
      })),
      createdBy: userStore.user?.id || 1 // 从用户状态获取用户ID
    }

    try
    {
      if (editingTemplate.value)
      {
        // 更新模板
        const response = await ApiClient.put(`/templates/${editingTemplate.value.id}`, templateData)
        if (response.success)
        {
          // 更新本地数据
          const index = templates.value.findIndex(t => t.id === editingTemplate.value.id)
          if (index > -1)
          {
            templates.value[index] = response.data
          }
          ElMessage.success('模板更新成功')
        } else
        {
          ElMessage.error('模板更新失败: ' + response.message)
          return
        }
      } else
      {
        // 创建新模板
        const response = await ApiClient.post('/templates', templateData)
        if (response.success)
        {
          // 添加到本地数据
          templates.value.unshift(response.data)
          ElMessage.success('模板创建成功')
        } else
        {
          ElMessage.error('模板创建失败: ' + response.message)
          return
        }
      }
    } catch (error)
    {
      console.error('保存模板失败:', error)

      // 提供更详细的错误信息
      let errorMessage = '保存模板失败'
      if (error.response?.data?.message)
      {
        errorMessage = error.response.data.message
      } else if (error.message)
      {
        errorMessage = error.message
      }

      ElMessage.error(errorMessage)
      return
    }

    showCreateDialog.value = false
    resetForm()

    // 刷新模板列表
    await fetchTemplates(true)
  } catch (error)
  {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板时发生未知错误')
  } finally
  {
    saving.value = false
  }
}

const importTemplate = () =>
{
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (event) =>
  {
    const file = event.target.files[0]
    if (file)
    {
      const reader = new FileReader()
      reader.onload = (e) =>
      {
        try
        {
          const template = JSON.parse(e.target.result)
          template.id = Date.now() // 生成新ID
          templates.value.unshift(template)
          ElMessage.success('模板导入成功')
        } catch (error)
        {
          ElMessage.error('模板文件格式错误')
        }
      }
      reader.readAsText(file)
    }
  }
  input.click()
}

const resetForm = () =>
{
  editingTemplate.value = null
  templateForm.value = {
    name: '',
    description: '',
    category: '',
    targetOs: '',
    tags: [],
    isPublic: true
  }
  // 重置tags相关状态
  inputVisible.value = false
  inputValue.value = ''

  if (formRef.value)
  {
    formRef.value.resetFields()
  }
}

const goToSoftwareSelection = () =>
{
  // 保存当前表单状态到sessionStorage
  const formState = {
    templateForm: templateForm.value,
    editingTemplate: editingTemplate.value,
    returnToCreateDialog: true
  }
  sessionStorage.setItem('templateFormState', JSON.stringify(formState))

  showCreateDialog.value = false
  router.push('/software')
}

const removeSoftwareFromTemplate = (softwareId) =>
{
  softwareStore.removeSoftware(softwareId)
}

// Tags相关方法
const showInput = () =>
{
  inputVisible.value = true
  nextTick(() =>
  {
    tagInput.value?.focus()
  })
}

const handleInputConfirm = () =>
{
  const value = inputValue.value.trim()
  if (value && !templateForm.value.tags.includes(value) && templateForm.value.tags.length < 5)
  {
    templateForm.value.tags.push(value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const removeTag = (tag) =>
{
  const index = templateForm.value.tags.indexOf(tag)
  if (index > -1)
  {
    templateForm.value.tags.splice(index, 1)
  }
}



const formatDate = (dateString) =>
{
  return new Date(dateString).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.template-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.template-card {
  height: fit-content;
  transition: all 0.3s ease;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.template-title {
  flex: 1;
}

.template-title h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.template-content {
  padding: 0;
}

.template-description {
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 16px;
}

.template-software {
  margin-bottom: 16px;
}

.template-software h4 {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.software-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.template-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #7f8c8d;
}

.template-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

.software-selection {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 12px;
  min-height: 80px;
}

.no-software {
  text-align: center;
  color: #7f8c8d;
  padding: 20px;
}

.selected-software-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.form-hint {
  margin-left: 8px;
  font-size: 12px;
  color: #7f8c8d;
}

.template-preview {
  max-height: 500px;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-management {
    padding: 0 10px;
  }

  .page-title {
    font-size: 24px;
  }

  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    width: 100%;
  }

  .search-section .el-input {
    width: 100% !important;
  }

  .action-buttons {
    justify-content: center;
  }

  .template-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .template-header {
    flex-direction: column;
    gap: 8px;
  }

  .template-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }

  .meta-item {
    font-size: 11px;
  }

  .software-tags .el-tag {
    font-size: 11px;
  }
}

/* Tags输入样式 */
.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  min-height: 32px;
}

.tags-tips {
  margin-top: 4px;
}

/* 软件选择样式 */
.software-selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.software-count {
  font-size: 14px;
  color: #606266;
}

.selected-software-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
